package com.atguigu.gmall.auth.config;

import com.atguigu.gmall.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Data
@Slf4j
@ConfigurationProperties(prefix = "jwt.auth")
public class JwtProperties implements InitializingBean {
    private String publicKeyFileName;
    private String privateKeyFileName;
    private String secret;
    private String cookieName;
    private String unickCookieName;
    private int expire;
    //因为上面加载的配置是公钥私钥的文件路径
    //还需要将文件加载转为 公钥私钥对象 代码中使用才比较方便
    private PublicKey publicKey;
    private PrivateKey privateKey;

//    @PostConstruct 当前类对象创建后立即执行 可以初始化
    // InitializingBean: spring提供的 在容器对象初始化后 提供一个立即执行的方法
    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            File pubkfile = new File(publicKeyFileName);
            File prikfile = new File(privateKeyFileName);
            if(!pubkfile.exists()|| !prikfile.exists()){
                RsaUtils.generateKey(publicKeyFileName,privateKeyFileName,secret);
            }
            this.publicKey = RsaUtils.getPublicKey(publicKeyFileName);
            this.privateKey = RsaUtils.getPrivateKey(privateKeyFileName);
        } catch (Exception e) {
            log.error("公钥私钥初始化失败: "+ ExceptionUtils.getStackTrace(e));
        }
    }

}
